<template>
  <!-- 注册和登录 -->
  <view class="login">
    <!-- 消息弹窗 -->
    <view>
      <u-toast ref="uToast" />
    </view>
    <view class="logo-wrap">
		
      <image src="@/static/logo.jpg" mode="widthFix" class="logo-img"></image>
      <view class="logo-text"> 欢迎登陆猿谋人博客 </view>
    </view>
      <!-- 表单 -->
    <view class="form">
      <u-form :model="userForm" ref="userForm" class="user-form">
        <!-- 昵称 -->
        <u-form-item
          prop="nickname"
          left-icon="account"
          :left-icon-style="leftIconStyle"
          v-if="istoRegister"
        >
          <u-input
            class="form-inp"
            v-model="userForm.nickname"
            border-color="#F2AE27"
            type="text"
            :border="true"
            placeholder="请输入昵称"
            maxlength="10"
          />
        </u-form-item>

        <!-- 手机号码 -->
        <u-form-item
          prop="phone"
          left-icon="phone"
          :left-icon-style="leftIconStyle"
        >
          <u-input
            class="form-inp"
            v-model="userForm.phone"
            border-color="#F2AE27"
            type="text"
            :border="true"
            placeholder="手机号码"
            maxlength="11"
          />
        </u-form-item>

        <!-- 密码 -->
        <u-form-item
          prop="password"
          left-icon="lock"
          :left-icon-style="leftIconStyle"
        >
          <u-input
            class="form-inp"
            v-model="userForm.password"
            border-color="#F2AE27"
            type="password"
            :border="true"
            placeholder="请输入密码"
            maxlength="32"
          />
        </u-form-item>

        <!-- 再次输入密码 -->
        <u-form-item
          prop="validPassword"
          left-icon="lock-fill"
          :left-icon-style="leftIconStyle"
          v-if="istoRegister"
        >
          <u-input
            class="form-inp"
            v-model="userForm.validPassword"
            border-color="#F2AE27"
            type="password"
            :border="true"
            placeholder="请再次输入密码"
            maxlength="32"
          />
        </u-form-item>
      </u-form>
    </view>
    <!-- 按钮部分 -->
    <view class="handle">
      <u-button
        :ripple="true"
        :disabled="handleBtnStyle.disabled"
        :custom-style="handleBtnStyle"
        @click="toLogin"
        >登录</u-button
      >
      <u-button
        :ripple="true"
        :disabled="handleBtnStyle.disabled"
        :custom-style="handleBtnStyle"
        @click="toRegister"
        >注册</u-button
      >
    </view>
  </view>
</template>

<script>
import { mapMutations } from 'vuex';
export default {
  data() {
    return {
      //	控制显示昵称输入框
      istoRegister: false,
      // 两个按钮的样式
      handleBtnStyle: {
        backgroundColor: '#F2AE27',
        color: '#fff',
        fontSize: '30rpx',
        fontWeight: '600',
        marginBottom: '15px',
        disabled: false,
      },
      // 两个form-item的icon样式
      leftIconStyle: {
        color: '#F2AE27',
        fontSize: '40rpx',
      },
      // 表单数据
      userForm: {
        // 手机号
        phone: '17835698086',
        // 密码
        password: '123456',
        // 昵称
        nickname: '',
        // 密码二次验证
        validPassword: '',
      },
      // 表单验证规则
      userFormRules: {
        // 昵称
        nickname: [
          {
            required: true, // 必填项
            message: '此为必填项',
            trigger: ['change', 'blur'], //触发验证方式
          },
          {
            min: 3,
            max: 10,
            message: '长度在3~10个字符',
            trigger: ['change', 'blur'], //触发验证方式
          },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z]{3,10}$/,
            // 正则检验前先将值转为字符串
            transform(value) {
              return String(value);
            },
            message: '只能包含中英文',
            trigger: ['change', 'blur'], //触发验证方式
          },
        ],
        // 手机号
        phone: [
          {
            required: true, // 必填项
            message: '此为必填项',
            trigger: ['change', 'blur'], //触发验证方式
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              return this.$u.test.mobile(value);
            },
            message: '手机号码不正确',
            trigger: ['change', 'blur'],
          },
        ],
        // 密码
        password: [
          {
            required: true, // 必填项
            message: '此为必填项',
            trigger: ['change', 'blur'], //触发验证方式
          },
          {
            min: 6,
            max: 16,
            message: '长度在6~16个字符',
            trigger: ['change', 'blur'], //触发验证方式
          },
          {
            pattern: /^[a-zA-Z0-9_-]{6,16}$/,
            // 正则检验前先将值转为字符串
            transform(value) {
              return String(value);
            },
            message: '只能由英文、数字、下划线组成',
            trigger: ['change', 'blur'], //触发验证方式
          },
        ],
        // 二次输入密码
        validPassword: [
          {
            required: true, // 必填项
            message: '此为必填项',
            trigger: ['change', 'blur'], //触发验证方式
          },
          {
            min: 6,
            max: 16,
            message: '长度在6~16个字符',
            trigger: ['change', 'blur'], //触发验证方式
          },
          {
            pattern: /^[a-zA-Z0-9_-]{6,16}$/,
            // 正则检验前先将值转为字符串
            transform(value) {
              return String(value);
            },
            message: '只能由英文、数字、下划线组成',
            trigger: ['change', 'blur'], //触发验证方式
          },
          {
            validator: (rule, value, callback) => {
              if (value == this.userForm.password) {
                return true;
              } else {
                return false;
              }
            },
            message: '两次输入的密码不一样,请检查~',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur'],
          },
        ],
      },
    };
  },
  methods: {
    ...mapMutations(['updataUserInfo']),
    // 注册
    toRegister() {
      if (!this.istoRegister) {
        // 昵称输入栏未显示
        return (this.istoRegister = true); // 显示昵称栏
      }
      // 禁用按钮
      this.handleBtnStyle.disabled = true;

      // 验证参数
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          try {
            // 发送注册
            let registerRes = await this._api.toRegister({
              name: this.userForm.nickname,
              phone: this.userForm.phone,
              password: this.userForm.password,
              projectId: 181,
            });
            this.$refs.uToast.show({
              title: '注册成功,将自动登录!',
              type: 'success',
              position: 'top',
              callback: () => {
                // 进行登录
                this.toLogin();
              },
            });
          } catch (e) {
            // 注册失败
            this.$refs.uToast.show({
              title: e.msg,
              type: 'error',
              position: 'top',
            });
          }
        } else {
          // 参数验证没通过
          this.$refs.uToast.show({
            title: '缺少必填项，请检查',
            type: 'error',
            position: 'top',
          });
        }

        // 启用按钮
        this.handleBtnStyle.disabled = false;
      });
    },
    // 登录
    toLogin() {
      //	禁用按钮
      this.handleBtnStyle.disabled = true;
      //  隐藏昵称输入栏
      this.istoRegister && (this.istoRegister = false);

      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          //  参数校验通过
          // 显示loading 使用uni的api方法
		  
          uni.showLoading({
            title: '登录中~',
            mask: true,
          });
          try {
            //  发送登录请求
            let loginRes = await this._api.toLogin({
              phone: this.userForm.phone,
              password: this.userForm.password,
            });
            // 	同步登录信息到vuex
            this.updataUserInfo(loginRes);
            // 隐藏Loding
            uni.hideLoading();
            this.$refs.uToast.show({
              title: '登录成功',
              type: 'success',
              position: 'top',
            });
            this.$emit('loginStateChange', {
              loginState: true,
            });
          } catch (e) {
            // 隐藏Loding
            uni.hideLoading();
            this.$refs.uToast.show({
              title: e.msg,
              type: 'error',
              position: 'top',
            });
          }
        } else {
          // 参数验证没通过
          this.$refs.uToast.show({
            title: '缺少必填项，请检查',
            type: 'error',
            position: 'top',
          });
        }
        // 启用按钮
        this.handleBtnStyle.disabled = false;
      });
    },
  },
  mounted() {
    // 表单校验
    this.$refs.userForm.setRules(this.userFormRules);
  },
  computed: {},
};
</script>

<style lang="scss" scoped>
.login {
  padding: 30px;
  background-color: #fff;
  border-radius: 20rpx;
  .logo-wrap {
    // width: 200rpx;
    margin: 0 auto;
    text-align: center;
    margin-bottom: 20px;
    .logo-img {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 15px;
    }
    .logo-text {
      font-size: 50rpx;
      font-weight: 600;
    }
  }
  .form {
    margin-bottom: 30px;
  }
}
</style>
